package com.udp;

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.text.SimpleDateFormat;
import java.util.Date;


public class UdpReceive {

    public static void main(String[] args) throws Exception {
        //开放端口
        DatagramSocket socket = new DatagramSocket(9090);

        //接收数据包
        byte[] buffer = new byte[1024];
        DatagramPacket packet = new DatagramPacket(buffer, 0, buffer.length);

        while (true) {

            //阻塞接收，即等待packet中填充数据后，程序再往下执行
            socket.receive(packet);

            //拆包
            System.out.println(packet.getAddress().getHostAddress());
            String msg = new String(packet.getData(),0,packet.getLength());
            System.out.println(msg);

            //显示当前格式化时间
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss:SSS");
            System.out.println(dateFormat.format(new Date()));

            if ("bye".equals(msg)){
                socket.close();
                break;
            }
        }
    }


}
